<template>
    <div class="snow-page">
        <a-card title="危险源信息添加" style="width: 99%" hoverable>
            <template #extra>
                <a-button size="mini" type="primary" @click="goBack">返回</a-button>
            </template>
            <div class="">
                <div class="snow-inner-page">
                    <a-row :gutter="16">
                        <a-form ref="formRef" :size="form.size" :model="form" auto-label-width @submit="handleSubmit">
                            <div style="display: flex">
                                <a-col :span="12">
                                    <a-form-item field="hazard_code" label="重大危险源编码" :rules="[{ required: true, message: '重大危险源编码不能为空' }]">
                                        <a-input v-model="form.hazard_code" placeholder="重大危险源编码" allow-clear  :disabled="editDisabled"/>
                                    </a-form-item>

                                    <a-form-item field="company_code" label="企业"
                                        :rules="[{ required: true, message: '企业不能为空' }]"
                                        :validate-trigger="['change', 'input']">
                                        <a-tree-select v-model="form.company_code" :field-names="filrname"
                                            :data="treeNodes" placeholder="企业" allow-clear></a-tree-select>
                                    </a-form-item>

                                    <a-form-item field="hazard_name" label="重大危险源名称"
                                        :rules="[{ required: true, message: '重大危险源名称不能为空' }]">
                                        <a-input v-model="form.hazard_name" placeholder="请输入重大危险源名称" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="hazard_short_name" label="重大危险源简称">
                                        <a-input v-model="form.hazard_short_name" placeholder="请输入重大危险源简称"
                                            allow-clear />
                                    </a-form-item>

                                    <a-form-item field="hazard_rank" label="危险源等级"
                                        :rules="[{ required: true, message: '危险源等级不能为空' }]">
                                        <a-select v-model="form.hazard_rank" placeholder="危险源等级" allow-clear>
                                            <a-option v-for="(item, index) in options597" :key="index"
                                                :value="item.id">{{ item.name
                                                }}</a-option>
                                        </a-select>
                                    </a-form-item>
                                    <a-form-item field="rvalue" label="R值"
                                        :rules="[{ required: true, message: 'R值不能为空' }]">
                                        <a-input v-model="form.rvalue" placeholder="请输入R值" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="area_code" label="行政区域编码"
                                        :rules="[{ required: true, message: '地区不能为空' }]">
                                        <a-cascader :options="regionData" v-model="form.area_code" placeholder="请选择地区"
                                            allow-clear allow-search />
                                    </a-form-item>

                                    <a-form-item field="address" label="地址"
                                        :rules="[{ required: true, message: '地址不能为空' }]">
                                        <a-input v-model="form.address" placeholder="请输入地址" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="lon" label="经度"
                                        :rules="[{ required: true, message: '经度不能为空' }]">
                                        <a-input v-model="form.lon" placeholder="请输入经度" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="lat" label="纬度"
                                        :rules="[{ required: true, message: '纬度不能为空' }]">
                                        <a-input v-model="form.lat" placeholder="请输入纬度" allow-clear />
                                    </a-form-item>

                                    <a-form-item field="establish_date" label="投用日期">
                                        <a-date-picker v-model="form.establish_date" placeholder="请选择投用日期"
                                            allow-clear />
                                    </a-form-item>


                                </a-col>

                                <a-col :span="12">
                                    <a-form-item field="protection_target_distance" label="周边防护目标最近距离（米）">
                                        <a-input v-model="form.protection_target_distance" placeholder="周边防护目标最近距离（米）"
                                            allow-clear />
                                    </a-form-item>
                                    <a-form-item field="people_500m" label="外边界500米范围人数估算">
                                        <a-input v-model="form.people_500m" placeholder="外边界500米范围人数估算" allow-clear>
                                        </a-input>
                                    </a-form-item>
                                    <a-form-item field="basic_info" label="库房基本信息">
                                        <a-input v-model="form.basic_info" placeholder="库房基本信息" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="max_storage" label="库房的最大储存量">
                                        <a-input v-model="form.max_storage" placeholder="库房的最大储存量" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="goods_type" label="库房储存物品类别">
                                        <a-input v-model="form.goods_type" placeholder="库房储存物品类别" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="safe_operation" label="库房安全操作规程">
                                        <a-input v-model="form.safe_operation" placeholder="库房安全操作规程" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="max_group" label="最大罐组">
                                        <a-input v-model="form.max_group" placeholder="最大罐组" allow-clear />
                                    </a-form-item>
                                    <a-form-item field="in_industrial_park" label="是否在化工园区内">
                                        <a-radio-group v-model="form.in_industrial_park" placeholder="是否在化工园区内"
                                            allow-clear>
                                            <a-radio value="1">是</a-radio>
                                            <a-radio value="0">否</a-radio>
                                        </a-radio-group>
                                    </a-form-item>
                                    <a-form-item field="is_dangerous" label="是否的重大危险源"  :rules="[{ required: true, message: '是否的重大危险源不能为空' }]">
                                        <a-radio-group v-model="form.is_dangerous" placeholder="是否的重大危险源"
                                            allow-clear>
                                            <a-radio value="0">一般</a-radio>
                                            <a-radio value="1">危险</a-radio>
                                            <a-radio value="2">重大危险</a-radio>
                                        </a-radio-group>
                                    </a-form-item>
                                    
                                    <a-form-item field="industrial_park_name" label="所属化工园区名称">
                                        <a-input v-model="form.industrial_park_name" placeholder="所属化工园区名称"
                                            allow-clear />
                                    </a-form-item>

                                </a-col>
                            </div>
                            <div style="text-align: center; margin-left: 35%">
                                <a-form-item>
                                    <a-space>
                                        <a-button type="primary" html-type="submit">提交</a-button>
                                        <a-button @click="onReset">重置</a-button>
                                    </a-space>
                                </a-form-item>
                            </div>
                        </a-form>
                    </a-row>
                </div>
            </div>

            <a-modal v-model:visible="mapopen" title="选择位置" width="50%">
                <div id="mapContainer" style="width: 100%; height: 400px"></div>
                <div class="input-container">
                    <input v-model="longitude" @keyup.enter="locatePosition" placeholder="输入经度"
                        class="coordinate-input" />
                    <input v-model="latitude" @keyup.enter="locatePosition" placeholder="输入纬度"
                        class="coordinate-input" />
                    <button @click="locatePosition" class="locate-button">定位</button>
                </div>
            </a-modal>
        </a-card>
    </div>
</template>


<script setup lang="ts">
import { Message } from "@arco-design/web-vue";
import { ref, reactive, onMounted } from "vue";
import { regionData } from "element-china-area-data";
import { getAllqiyeAPI } from "@/api/modules/qiye/index";
import { addweixianAPI,updateweixianAPI } from "@/api/modules/weixian/index";
import { getDictBycodeAPI } from "@/api/modules/dictionary/index";
// import axios from "axios";
const router = useRouter();
onMounted(() => {
    getDictBycodeAPIfun();
    getDictBycodeAPIfun2();
    getInit();
    getFuzhi();
});

const options597 = ref([]);
async function getDictBycodeAPIfun() {
    // let obj={}
    let res = await getDictBycodeAPI(597);
    if (res.status == 2) {
        options597.value = res.data;
    }
}
const options558 = ref([]);
async function getDictBycodeAPIfun2() {
    let res = await getDictBycodeAPI(558);
    if (res.status == 2) {
        options558.value = res.data;
    }
}




function getFuzhi() {
    let userInfo = JSON.parse(localStorage.getItem("user-info") as string);
    if (userInfo) {
        editDisabled.value = true
        form.id = userInfo.sharedObject.id;
        form.company_code = userInfo.sharedObject.company_code;
        form.hazard_code = userInfo.sharedObject.hazard_code;
        form.hazard_name = userInfo.sharedObject.hazard_name;
        form.hazard_short_name = userInfo.sharedObject.hazard_short_name;
       
        form.hazard_rank = parseInt(userInfo.sharedObject.hazard_rank);
        form.rvalue = userInfo.sharedObject.rvalue;
        form.area_code = userInfo.sharedObject.area_code ? userInfo.sharedObject.area_code : undefined;
        form.address = userInfo.sharedObject.address;
        form.lon = userInfo.sharedObject.lon;
        form.lat = userInfo.sharedObject.lat;
        form.establish_date = userInfo.sharedObject.establish_date;
        form.protection_target_distance = userInfo.sharedObject.protection_target_distance;
        form.people_500m = userInfo.sharedObject.people_500m;
        form.basic_info = userInfo.sharedObject.basic_info;
        form.max_storage = userInfo.sharedObject.max_storage;
        form.goods_type = userInfo.sharedObject.goods_type;
        form.safe_operation = userInfo.sharedObject.safe_operation;
        form.max_group = userInfo.sharedObject.max_group;
        form.iot_node_type = userInfo.sharedObject.iot_node_type;
        
        if(userInfo.sharedObject.in_industrial_park=="1"||userInfo.sharedObject.in_industrial_park=="0"){
            form.in_industrial_park = userInfo.sharedObject.in_industrial_park+'';
        }
        if(userInfo.sharedObject.is_dangerous=="1"||userInfo.sharedObject.is_dangerous=="0" ||userInfo.sharedObject.is_dangerous=="2"){
            form.is_dangerous = userInfo.sharedObject.is_dangerous+'';
        }
        
       
        form.industrial_park_name = userInfo.sharedObject.industrial_park_name;
    }
}

const mapopen = ref(false);

const editDisabled = ref(false)

const treeNodes = ref([]);

async function getInit() {
    let obj = {};
    let res = await getAllqiyeAPI(obj);
    if (res.status == 2) {
        treeNodes.value = generateTreeNodes(res.data);
    }
}

const filrname = ref({
    key: "id",
    value: "id",
    title: "name",
    children: "children"
});

function generateTreeNodes(data) {
    const nodeMap = new Map();
    const rootNodes = [];

    // First pass: create nodes and store them in a map
    data.forEach(item => {
        const node = {
            id: item.cq_company_code,
            name: item.name,
            children: [],
            data: item // Store all original data
        };
        nodeMap.set(item.cq_company_code, node);
    });

    // Second pass: build the tree structure
    data.forEach(item => {
        const node = nodeMap.get(item.cq_company_code);
        if (item.cq_parent_code === "0") {
            rootNodes.push(node);
        } else {
            const parentNode = nodeMap.get(item.cq_parent_code);
            if (parentNode) {
                parentNode.children.push(node);
            } else {
                console.warn(`Parent node ${item.cq_parent_code} not found for ${item.cq_company_code}`);
                rootNodes.push(node); // Add to root if parent not found
            }
        }
    });

    return rootNodes;
}

const handleSubmit = async ({ values, errors }) => {
    if (errors) {
        return;
    }
    let res: any = "";
    if (form.id) {
        res = (await updateweixianAPI(values)) as any;
    } else {
        res = (await addweixianAPI(values)) as any;
    }

    if (res.status == 2) {
        // router.back();
        Message.error("操作成功");
    } else {
        Message.error(res.statusMsg);
    }
};

// 将序列化的字符串美观输出，\t 换行

const form = reactive({}) as any;

const formRef = ref();
const onReset = () => {
    formRef.value.resetFields();
};

function goBack() {
    router.back();
}

function onSearch() {
    mapopen.value = true;

    setTimeout(function () {
        initMap();
    }, 500);
}
const longitude = ref("");
const latitude = ref("");
const map = ref({}) as any;
let marker: any;
const locatePosition = () => {
    const lon = parseFloat(longitude.value);
    const lat = parseFloat(latitude.value);

    form.lonLat = lon + "," + lat;
    if (isNaN(lon) || isNaN(lat)) {
        alert("请输入有效的经纬度");
        return;
    }

    const lnglat = new window.T.LngLat(lon, lat);

    // 移动地图中心
    map.value.panTo(lnglat);

    // 清除现有标记
    map.value.clearOverLays();

    // 添加新标记
    marker = new window.T.Marker(lnglat);
    map.value.addOverLay(marker);

    // 设置缩放级别
    map.value.setZoom(13);
};
function initMap() {
    //map创建地图实例

    map.value = new T.Map(document.getElementById("mapContainer"));

    // 设置地图中心点和缩放级别
    map.value.centerAndZoom(new T.LngLat(121.42638, 31.63153), 11);

    map.value.on("click", function (e) {
        map.value.clearOverLays();
        longitude.value = e.lnglat.lng;
        latitude.value = e.lnglat.lat;
        form.lonLat = e.lnglat.lng + "," + e.lnglat.lat;

        // getAddressInfo();
        const position = new T.LngLat(e.lnglat.lng, e.lnglat.lat);
        let icon = new T.Icon({
            iconUrl: "./icon.png", // 请求图标图片的URL
            iconSize: new T.Point(40, 40), // 图标可视区域的大小
            iconAnchor: new T.Point(30, 30) // 图标的定位锚点
        });
        const marker = new T.Marker(position, { icon: icon });
        map.value.addOverLay(marker);
    });
}

// async function getAddressInfo() {
//   let Tokens = "20f5dad7c9e6207216d4d7d971fbed3f";
//   let postStr = {
//     lon: form.lon,
//     lat: form.lat,
//     ver: 1
//   };
//   let url = "https://api.tianditu.gov.cn/geocoder";
//   // Lambda写法
//   let res = await axios({
//     method: "get",
//     url: url,
//     params: {
//       postStr: JSON.stringify(postStr),
//       type: "geocode",
//       tk: Tokens
//     },
//     timeout: 1000
//   });
//   // 响应成功回调
//   if (res.data.msg == "ok") {
//     form.cq_address_worksite = res.data.result.formatted_address;
//   }
// }
</script>

<style lang="scss">
.arco-input-wrapper .arco-input[disabled] {
    -webkit-text-fill-color: #8f7e7e !important;
}

.arco-form-item {
    margin-bottom: 10px !important;
}

.arco-input-wrapper.arco-input-disabled .arco-input-prefix,
.arco-input-wrapper.arco-input-disabled .arco-input-suffix {
    color: #000 !important;
}

.input-container {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    display: flex;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 10px;
    border-radius: 4px;
}

.coordinate-input {
    padding: 8px;
    font-size: 14px;
    border: 1px solid #ccc;
    border-radius: 4px;
    width: 120px;
    margin-right: 5px;
}

.locate-button {
    padding: 8px 16px;
    font-size: 14px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.locate-button:hover {
    background-color: #45a049;
}
</style>